#!/usr/bin/env python

""" Ajaxterm """

import array,cgi,fcntl,glob,mimetypes,optparse,os,pty,random,re,signal,select,sys,threading,time,termios,struct,pwd

os.chdir(os.path.normpath(os.path.dirname(__file__)))
# Optional: Add QWeb in sys path
sys.path[0:0]=glob.glob('../../python')

import qweb
from itertools import *
import json,subprocess


class AjaxTerm:
	def __init__(self):
		self.index_file='ajaxterm.html'
		self.files={}
		
		for i in ['css','html','js']:
			for j in glob.glob('*.%s'%i):
				self.files[j]=file(j).read()
		self.files['index']=file(self.index_file).read()
		self.mime = mimetypes.types_map.copy()
		self.mime['.html']= 'text/html; charset=UTF-8'
		self.session = {}
		self.activeCount=0
		self.seqCount = 0
		p = subprocess.Popen("groovysh", shell=True, bufsize=1024, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, close_fds=True)
		(self.w, self.r) = (p.stdin, p.stdout)

		# ret = 0A

	def __call__(self, environ, start_response):
		self.activeCount += 1
		req = qweb.QWebRequest(environ, start_response,session=None)
		print 'Request ', req.REQUEST, req.FULL_URL
		reply = {}
		if req.POST:
			self.seqCount += 1
			reply["sequence"] = self.seqCount
			reply["session"] = "bsVGwKuustmNJKQK3HL2gA"
			if not req.REQUEST["session"]:
				#reply["data"] = "Welcome to pyterm!"
				pass
			else:
				if req.FULL_PATH == '/reqURL':
					print 'Reading...(', self.seqCount, ')'
					txt = os.read(self.r.fileno(), 1024)
					#txt = self.r.read(1024)
					print 'Read', txt, '...(', self.seqCount, ')'
					reply["data"] = txt.replace('\n', '\r\n')
				if req.FULL_PATH == '/keyURL':
					keys = req.REQUEST["keys"]
					chars = [chr(int("".join(key), 16)) for key in pairs(keys)]				
					os.write(self.w.fileno(), "".join(chars))
					#self.w.write("".join(chars))
				
			req.response_headers['Content-Type'] = 'application/json; charset=utf-8'	
			req.response_headers['Content-Length'] = len(reply)
			print 'Reply', reply, json.write(reply), self.activeCount
			req.write(json.write(reply))
			
		else:
			n=os.path.basename(req.PATH_INFO)
			if n in self.files:
				req.response_headers['Content-Type'] = self.mime.get(os.path.splitext(n)[1].lower(), 'application/octet-stream')
				req.write(self.files[n])
			else:
				req.response_headers['Content-Type'] = 'text/html; charset=UTF-8'
				req.write(self.files['index'])
		self.activeCount -= 1		
		return req

def pairs(x):
	xiter = iter(x)
	return izip(xiter,xiter)


def main():
	print 'In main...'	
	print 'AjaxTerm at http://localhost:%s/' % 8022
	at=AjaxTerm()
	try:
		qweb.QWebWSGIServer(at,ip='localhost',port=8022,threaded=1).serve_forever()
	except KeyboardInterrupt,e:
		sys.excepthook(*sys.exc_info())

if __name__ == '__main__':
	print 'Starting...'
	main()

